package com.gc.web.controller.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gc.business.domain.*;
import com.gc.business.service.*;
import com.gc.common.constant.Constants;
import com.gc.common.utils.StringUtils;
import com.gc.framework.web.base.ApiBaseController;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysUserService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 积分商品 控制层
 *
 * @author liujinteng
 * @date 2021-01-09
 */
@Slf4j
@Controller
@RequestMapping("/api/myIntegral")
public class ApiMyIntegralController extends ApiBaseController {


    @Autowired
    private ISysUserService userService;

    @Autowired
    private IIntegralGoodsService integralGoodsService;

    @Autowired
    private IIntegralConfigService integralConfigService;

    @Autowired
    private IIntegralDetailService integralDetailService;

    @Autowired
    private IIntegralOrderService integralOrderService;

    @Autowired
    private IAttachmentService attachmentService;


    /**
     * 查询积分商品接口
     *
     * @param token
     * @param sortFiled 0:推荐_时间;1:积分
     * @param sortRule  0-ASC:正序;1-DESC:倒序
     * @return
     */
    @GetMapping("/selectGoodsList")
    @ResponseBody
    public Map<String, Object> selectGoodsList(String token, int sortFiled, Integer pageNum, Integer pageSize, String sortRule) {
        SysUser sysUser = userService.selectUserById(getUserId(token));
        if (sortRule.equals("0")) {
            sortRule = "ASC";
        } else if (sortRule.equals("1")) {
            sortRule = "DESC";
        }
        if (sortFiled == 0) {
            startPage(pageNum, pageSize, "create_time " + sortRule);
        } else if (sortFiled == 1) {
            startPage(pageNum, pageSize, "exchange_score " + sortRule);
        }
        List<IntegralGoods> integralGoodsList = integralGoodsService.selectGoodsByCompanyId(sysUser.getAttrId(), null, null);
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("list", integralGoodsList);
        map.put("total", new PageInfo<>(integralGoodsList).getTotal());
        return success(map);
    }


    /**
     * 获取积分规则
     *
     * @param token
     * @return
     */
    @GetMapping("/selectIntegralRules")
    @ResponseBody
    public Map<String, Object> selectIntegralRules(String token) {
        SysUser sysUser = userService.selectUserById(getUserId(token));
        LambdaQueryWrapper<IntegralConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IntegralConfig::getCompanyId, sysUser.getAttrId());
        IntegralConfig integralConfig = integralConfigService.getOne(wrapper);
        if (integralConfig == null) {
            return error(Constants.UNVERIFY, "积分规则不存在");
        }
        return success(integralConfig);
    }


    /**
     * 查看积分明细
     *
     * @param token
     * @param yearMonth 格式:yyyy-MM
     * @return
     */
    @GetMapping("/selectIntegralDetailList")
    @ResponseBody
    public Map<String, Object> selectIntegralDetailList(String token, String yearMonth, Integer pageNum, Integer pageSize) {
        SysUser sysUser = userService.selectUserById(getUserId(token));
        LambdaQueryWrapper<IntegralDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IntegralDetail::getUserId, sysUser.getUserId());
        wrapper.apply("DATE_FORMAT(create_time,'%Y-%m')= {0}", yearMonth);
        startPage(pageNum, pageSize, "create_time desc");
        List<IntegralDetail> detailList = integralDetailService.list(wrapper);
        return success(detailList);
    }

    /**
     * 积分排行榜
     *
     * @return
     */
    @GetMapping("/rankUserListByScore")
    @ResponseBody
    public Map<String, Object> rankUserListByScore(String yearMonth, String token, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(yearMonth)) {
            yearMonth = DateUtil.format(new Date(), "YYYY-MM");
        }
        SysUser sysUser = userService.selectUserById(getUserId(token));
        startPage(pageNum, pageSize, "create_time desc");
        List<SysUser> selectUserList = userService.selectUserByAttrId(sysUser.getAttrId());
        //List<SysUser> selectUserList = userService.selectUserList(user);
        for (SysUser user : selectUserList) {
            //查询该用户指定日期前的积分数量
            Integer score = integralDetailService.selectScoreByMonth(yearMonth, user.getUserId());
            if (score == null) {
                score = 0;
            }
            user.setOwnScore(score + "");
        }
        //倒叙
        selectUserList.sort((o1, o2) -> Integer.valueOf(o2.getOwnScore()).compareTo(Integer.valueOf(o1.getOwnScore())));
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("list", selectUserList);
        map.put("total", new PageInfo<>(selectUserList).getTotal());
        return success(map);
    }

    /**
     * 查看商品详情
     *
     * @return
     */
    @GetMapping("/selectGoodsIntegralInfo")
    @ResponseBody
    public Map<String, Object> selectGoodsIntegralInfo(Long goodsId) {
        if (goodsId == null) {
            return error(Constants.UNVERIFY, "参数错误:goodsId不存在");
        }
        IntegralGoods integralGoods = integralGoodsService.getById(goodsId);
        if (integralGoods == null) {
            return error(Constants.UNVERIFY, "商品信息有误!!!");
        }
        List<Attachment> attachmentList = new ArrayList<>();
        if (StringUtils.isNotEmpty(integralGoods.getGoodsRolling()) && !integralGoods.getGoodsRolling().contains(",")){
            Attachment attachment = attachmentService.getById(integralGoods.getGoodsRolling());
            if (attachment != null){
                attachmentList.add(attachment);
            }
        }else if (StringUtils.isNotEmpty(integralGoods.getGoodsRolling()) && integralGoods.getGoodsRolling().contains(",")){
            String[] attachIds = integralGoods.getGoodsRolling().split(",");
            for (String attachId : attachIds) {
                Attachment attachment = attachmentService.getById(attachId);
                if (attachment != null){
                    attachmentList.add(attachment);
                }

            }
        }
        integralGoods.setGoodsRollingList(attachmentList);
        return success(integralGoods);
    }

    /**
     * 立即兑换(预览订单 -- 未生成订单)
     *
     * @param token
     * @param goodsId
     * @param exchangeCount
     * @return
     */
    @GetMapping("/immediatelyExchange")
    @ResponseBody
    public Map<String, Object> immediatelyExchange(String token, Long goodsId, int exchangeCount) {
        SysUser sysUser = userService.selectUserById(getUserId(token));
        if (goodsId == null) {
            return error(Constants.UNVERIFY, "参数错误:goodsId不存在");
        }
        IntegralGoods integralGoods = integralGoodsService.getById(goodsId);
        if (integralGoods == null) {
            return error(Constants.UNVERIFY, "商品信息有误");
        }
        if (Integer.parseInt(sysUser.getOwnScore()) < integralGoods.getExchangeScore()) {
            return error(Constants.UNVERIFY, "积分不足");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("user", sysUser);//用户信息
        map.put("integralGoods", integralGoods);//商品信息
        map.put("exchangeCount", exchangeCount);//兑换数量
        //计算合计积分数
        String total = NumberUtil.mul(exchangeCount + "", integralGoods.getExchangeScore().toString()).stripTrailingZeros().toPlainString();
        map.put("total", total);//合计
        return success(map);
    }

    /**
     * 下单兑换接口
     *
     * @return
     */
    @PostMapping("/orderExchange")
    @ResponseBody
    public Map<String, Object> orderExchange(String token, Long goodsId, int exchangeCount) {
        SysUser sysUser = userService.selectUserById(getUserId(token));
        if (goodsId == null) {
            return error(Constants.UNVERIFY, "参数错误:goodsId不存在");
        }
        IntegralGoods integralGoods = integralGoodsService.getById(goodsId);
        if (integralGoods == null) {
            return error(Constants.UNVERIFY, "商品信息有误");
        }
        if (Integer.parseInt(sysUser.getOwnScore()) < integralGoods.getExchangeScore()) {
            return error(Constants.UNVERIFY, "积分不足");
        }
        Boolean result = integralOrderService.saveOrder(sysUser, integralGoods, exchangeCount);
        if (!result) {
            return error(Constants.UNVERIFY, "下单失败");
        }
        return success("下单成功");
    }

    //订单列表
    @PostMapping("/selectOrderList")
    @ResponseBody
    public Map<String, Object> orderExchange(String token, Integer pageNum, Integer pageSize) {
        Long userId = getUserId(token);
        IntegralOrder integralOrder = new IntegralOrder().setUserId(userId);
        startPage(pageNum, pageSize, "exchange_time desc");
        List<IntegralOrder> integralOrderList = integralOrderService.list(integralOrder);
        for (IntegralOrder order : integralOrderList) {
            order.setIntegralGoods(integralGoodsService.getById(order.getGoodsId()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("list", integralOrderList);
        map.put("total", new PageInfo<>(integralOrderList).getTotal());
        return success(map);
    }
}
